﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json.Linq;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;

namespace MesProjectWinform.BasicData.基础实现.Bom
{
    public partial class BomUp : DevExpress.XtraEditors.XtraForm
    {
        // API服务端口号怎
        private const string ApiBaseUrl = "http://47.110.243.157:5052/";
        // 保存父窗体引用，用于刷新父窗体数据
        private Bom _parentForm;
        
        // 无人机产品项字典，存储编码和名称的对应关系
        private Dictionary<string, string> _droneProducts;
        
        // BOM类型和阶别的映射字典，根据编码确定类型和阶别
        private Dictionary<string, Tuple<string, string>> _bomTypeRankMapping;
        
        // BOM类型的层级关系，数字越小层级越高
        private Dictionary<string, int> _bomTypeHierarchy;
        
        // 当前父BOM的类型，用于过滤可选的子BOM类型
        private string _parentBomType = "";
        
        // 当前编辑的BOM对象
        private Bommodel _currentBom;
        
        // 父BOM的ID，用于添加子BOM
        private long _parentBomId = 0;
        
        // 是否是添加子BOM模式
        private bool _isAddChildMode = false;
        
        public BomUp(Bom parentForm = null)
        {
            InitializeComponent();
            _parentForm = parentForm;
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化BOM类型层级关系
            InitializeBomTypeHierarchy();
            
            // 初始化无人机产品项字典
            InitializeDroneProducts();
            
            // 初始化BOM类型和阶别映射
            InitializeBomTypeRankMapping();
            
            // 初始化控件
            InitializeControls();
            
            // 加载产品项数据到下拉框
            LoadProductItems();
        }
        
        /// <summary>
        /// 用于编辑现有BOM的构造函数
        /// </summary>
        /// <param name="parentForm">父窗体</param>
        /// <param name="bom">要编辑的BOM对象</param>
        public BomUp(Bom parentForm, Bommodel bom)
        {
            InitializeComponent();
            _parentForm = parentForm;
            _currentBom = bom;
            
            // 初始化BOM类型层级关系
            InitializeBomTypeHierarchy();
            
            // 初始化无人机产品项字典
            InitializeDroneProducts();
            
            // 初始化BOM类型和阶别映射
            InitializeBomTypeRankMapping();
            
            // 初始化控件
            InitializeControls();
            
            // 加载产品项数据到下拉框
            LoadProductItems();
            
            // 如果是编辑模式，加载当前BOM数据到表单
            if (_currentBom != null)
            {
                LoadBomData();
            }
        }
        
        /// <summary>
        /// 初始化BOM类型层级关系
        /// </summary>
        private void InitializeBomTypeHierarchy()
        {
            // 创建BOM类型层级关系字典，数字越小层级越高
            _bomTypeHierarchy = new Dictionary<string, int>
            {
                { "成品", 1 },
                { "半成品", 2 },
                { "原材料", 3 }
            };
        }
        
        /// <summary>
        /// 初始化无人机产品项字典
        /// </summary>
        private void InitializeDroneProducts()
        {
            _droneProducts = new Dictionary<string, string>
            {
                { "", "" },
                { "UAV001", "无人机整机" },
                { "UAV002", "无人机机身" },
                { "UAV003", "无人机电机" },
                { "UAV004", "无人机螺旋桨" },
                { "UAV005", "无人机电池" },
                { "UAV006", "无人机控制板" },
                { "UAV007", "无人机摄像头" },
                { "UAV008", "无人机遥控器" }
            };
        }
        
        /// <summary>
        /// 初始化BOM类型和阶别映射
        /// </summary>
        private void InitializeBomTypeRankMapping()
        {
            // 创建映射字典，存储编码对应的类型和阶别
            // Tuple的Item1是BOM类型，Item2是阶别
            _bomTypeRankMapping = new Dictionary<string, Tuple<string, string>>
            {
                { "", new Tuple<string, string>("", "0") },
                { "UAV001", new Tuple<string, string>("成品", "0") },
                { "UAV002", new Tuple<string, string>("半成品", "0") },
                { "UAV003", new Tuple<string, string>("原材料", "0") },
                { "UAV004", new Tuple<string, string>("原材料", "0") },
                { "UAV005", new Tuple<string, string>("原材料", "0") },
                { "UAV006", new Tuple<string, string>("原材料", "0") },
                { "UAV007", new Tuple<string, string>("半成品", "0") },
                { "UAV008", new Tuple<string, string>("半成品", "0") }
            };
        }
        
        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitializeControls()
        {
            try
            {
                // 设置编码控件为下拉框
                textEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                
                // 为编码下拉框添加选择事件
                textEdit1.Properties.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.codeEdit_ButtonClick);
                textEdit1.Properties.Buttons.Clear();
                textEdit1.Properties.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo));
                
                // 为编码下拉框添加选择变更事件
                textEdit1.EditValueChanged += new EventHandler(this.codeEdit_EditValueChanged);
                
                // 添加按钮事件
                button1.Click += new EventHandler(this.button1_Click); // 重置按钮
                
                // 按钮2(保存)的点击事件已在Designer中注册，这里不需要重复注册
                // button2.Click += new EventHandler(this.button2_Click); // 保存按钮
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"初始化控件异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 编码下拉框按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void codeEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 可以在这里添加额外逻辑，如果需要的话
        }
        
        /// <summary>
        /// 编码下拉框值变更事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void codeEdit_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                // 获取选中的产品项编码
                string selectedCode = textEdit1.Text.Trim();
                
                if (!string.IsNullOrEmpty(selectedCode))
                {
                    // 根据编码获取产品项名称
                    if (_droneProducts.TryGetValue(selectedCode, out string productName))
                    {
                        // 设置名称
                        textEdit2.Text = productName;
                        
                        // 设置版本和描述为默认值
                        textEdit3.Text = "1.0"; // 默认版本
                        textEdit4.Text = $"{productName}的BOM信息";
                    }
                    else
                    {
                        XtraMessageBox.Show("未找到匹配的产品项信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"获取产品项信息异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载产品项数据到下拉框
        /// </summary>
        private void LoadProductItems()
        {
            try
            {
                // 清空下拉框
                textEdit1.Properties.Items.Clear();
                
                // 添加空选项
                textEdit1.Properties.Items.Add(" ");
                
                // 如果是添加子BOM模式，根据父BOM类型过滤可选的子BOM类型
                if (_isAddChildMode && !string.IsNullOrEmpty(_parentBomType) && _bomTypeHierarchy.ContainsKey(_parentBomType))
                {
                    int parentTypeLevel = _bomTypeHierarchy[_parentBomType];
                    
                    // 只添加层级比父BOM低的产品项
                    foreach (var item in _droneProducts.Keys)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            // 获取产品项的BOM类型
                            var typeRank = GetBomTypeAndRankByCode(item);
                            string bomType = typeRank.Item1;
                            
                            // 检查BOM类型是否在层级字典中
                            if (_bomTypeHierarchy.ContainsKey(bomType))
                            {
                                int bomTypeLevel = _bomTypeHierarchy[bomType];
                                
                                // 只添加层级比父BOM低的产品项（数字更大表示层级更低）
                                if (bomTypeLevel > parentTypeLevel)
                                {
                                    textEdit1.Properties.Items.Add(item);
                                }
                            }
                        }
                    }
                    
                    // 显示提示信息
                    Label lblFilterInfo = new Label();
                    lblFilterInfo.AutoSize = true;
                    lblFilterInfo.Text = $"已根据父BOM类型({_parentBomType})过滤可选项";
                    lblFilterInfo.Location = new Point(textEdit1.Location.X, textEdit1.Location.Y - 20);
                    lblFilterInfo.ForeColor = Color.Blue;
                    this.Controls.Add(lblFilterInfo);
                    lblFilterInfo.BringToFront();
                }
                else
                {
                    // 非子BOM模式，添加所有产品项
                    foreach (var item in _droneProducts.Keys)
                    {
                        textEdit1.Properties.Items.Add(item);
                    }
                }
                
                // 设置默认选择第一项
                if (textEdit1.Properties.Items.Count > 0)
                {
                    textEdit1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载产品项数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 根据编码获取BOM类型和阶别
        /// </summary>
        /// <param name="bomCode">BOM编码</param>
        /// <returns>包含BOM类型和阶别的元组</returns>
        private Tuple<string, string> GetBomTypeAndRankByCode(string bomCode)
        {
            if (_bomTypeRankMapping.TryGetValue(bomCode, out var typeRank))
            {
                return typeRank;
            }
            
            // 默认返回成品和0阶别
            return new Tuple<string, string>("成品", "0");
        }
        
        /// <summary>
        /// 加载当前BOM数据到表单
        /// </summary>
        private void LoadBomData()
        {
            try
            {
                if (_currentBom != null)
                {
                    // 设置表单控件的值
                    textEdit1.Text = _currentBom.Bomcode;
                    textEdit2.Text = _currentBom.Bomname;
                    textEdit3.Text = _currentBom.Bomversion;
                    textEdit4.Text = _currentBom.Bomdescription;
                    
                    // 添加调试日志
                    Console.WriteLine($"加载BOM数据 - ID: {_currentBom.Id}, 编码: {_currentBom.Bomcode}, 名称: {_currentBom.Bomname}");
                    Console.WriteLine($"BOM类型: {_currentBom.BomType}, 阶别: {_currentBom.Bomranks}, 工序编码: {_currentBom.Processmanagementcode}");
                    
                    // 打印完整的BOM对象信息
                    PrintBomDetails(_currentBom);
                    
                    // 修改表单标题
                    this.Text = "编辑BOM - " + _currentBom.Bomcode;
                    
                    // 如果编码在下拉列表中不存在，则添加它
                    if (!textEdit1.Properties.Items.Contains(_currentBom.Bomcode))
                    {
                        textEdit1.Properties.Items.Add(_currentBom.Bomcode);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载BOM数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载BOM数据异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 打印BOM对象的详细信息（用于调试）
        /// </summary>
        /// <param name="bom">BOM对象</param>
        private void PrintBomDetails(Bommodel bom)
        {
            if (bom == null)
            {
                Console.WriteLine("BOM对象为空");
                return;
            }
            
            try
            {
                Console.WriteLine("========== BOM详细信息 ==========");
                Console.WriteLine($"ID: {bom.Id}");
                Console.WriteLine($"编码: {bom.Bomcode}");
                Console.WriteLine($"名称: {bom.Bomname}");
                Console.WriteLine($"版本: {bom.Bomversion}");
                Console.WriteLine($"描述: {bom.Bomdescription}");
                Console.WriteLine($"产品项ID: {bom.Productitemid}");
                Console.WriteLine($"BOM类型: {bom.BomType}");
                Console.WriteLine($"BOM阶别: {bom.Bomranks}");
                Console.WriteLine($"工序编码: {bom.Processmanagementcode}");
                Console.WriteLine($"工序名称: {bom.Processmanagementname}");
                Console.WriteLine($"用量: {bom.Bomdosage}");
                Console.WriteLine($"父级ID: {bom.Parentid}");
                Console.WriteLine($"创建人: {bom.CreatedBy}");
                Console.WriteLine($"创建时间: {bom.CreatedTime}");
                Console.WriteLine($"更新人: {bom.UpdatedBy}");
                Console.WriteLine($"更新时间: {bom.UpdatedTime}");
                Console.WriteLine($"是否删除: {bom.IsDeleted}");
                Console.WriteLine("================================");
                
                // 将BOM对象序列化为JSON并打印（更完整的信息）
                string jsonData = JsonConvert.SerializeObject(bom, Formatting.Indented);
                Console.WriteLine("BOM对象JSON格式:");
                Console.WriteLine(jsonData);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打印BOM详细信息异常: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 清空所有输入框
            textEdit1.Text = string.Empty;
            textEdit2.Text = string.Empty;
            textEdit3.Text = string.Empty;
            textEdit4.Text = string.Empty;
        }
        
        /// <summary>
        /// 设置父BOM ID，用于添加子BOM
        /// </summary>
        /// <param name="parentId">父BOM的ID</param>
        public void SetParentBomId(long parentId)
        {
            _parentBomId = parentId;
            _isAddChildMode = true;
            
            // 更新窗体标题
            this.Text = "添加下级BOM";
            
            Console.WriteLine($"设置父BOM ID: {parentId}，进入添加下级模式");
            
            // 获取父BOM类型，用于过滤可选的子BOM类型
            GetParentBomType(parentId);
        }
        
        /// <summary>
        /// 获取父BOM的类型
        /// </summary>
        /// <param name="parentId">父BOM的ID</param>
        private async void GetParentBomType(long parentId)
        {
            try
            {
                // 构建API URL来获取父BOM信息
                string parentUrl = $"api/Bom/GetBomById?id={parentId}";
                
                // 使用HttpClient获取父BOM信息
                using (HttpClient parentClient = new HttpClient())
                {
                    parentClient.BaseAddress = new Uri(ApiBaseUrl);
                    parentClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    HttpResponseMessage parentResponse = await parentClient.GetAsync(parentUrl);
                    
                    if (parentResponse.IsSuccessStatusCode)
                    {
                        string parentResponseContent = await parentResponse.Content.ReadAsStringAsync();
                        JObject parentJson = JObject.Parse(parentResponseContent);
                        
                        // 检查响应状态码
                        string parentCode = parentJson["Code"]?.ToString();
                        if (parentCode == "200")
                        {
                            // 获取父BOM数据
                            JObject parentData = parentJson["Data"] as JObject;
                            if (parentData != null)
                            {
                                // 获取父BOM的类型
                                _parentBomType = parentData["BomType"]?.ToString() ?? "";
                                Console.WriteLine($"获取到父BOM类型: {_parentBomType}");
                                
                                // 重新加载产品项数据，根据父BOM类型过滤
                                LoadProductItems();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取父BOM类型异常: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 验证子BOM类型是否合法
        /// </summary>
        /// <param name="parentId">父BOM的ID</param>
        /// <param name="childBomType">子BOM的类型</param>
        /// <returns>验证结果，true表示合法，false表示不合法</returns>
        private async Task<bool> ValidateChildBomType(long parentId, string childBomType)
        {
            try
            {
                // 如果不是添加子BOM模式，则不需要验证
                if (!_isAddChildMode || parentId <= 0)
                {
                    return true;
                }

                // 如果子BOM类型不在层级字典中，无法验证，默认通过
                if (!_bomTypeHierarchy.ContainsKey(childBomType))
                {
                    return true;
                }
                
                // 获取子BOM类型的层级
                int childTypeLevel = _bomTypeHierarchy[childBomType];

                // 构建API URL来获取父BOM信息
                string parentUrl = $"api/Bom/GetBomById?id={parentId}";
                
                // 使用HttpClient获取父BOM信息
                using (HttpClient parentClient = new HttpClient())
                {
                    parentClient.BaseAddress = new Uri(ApiBaseUrl);
                    parentClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    HttpResponseMessage parentResponse = await parentClient.GetAsync(parentUrl);
                    
                    if (parentResponse.IsSuccessStatusCode)
                    {
                        string parentResponseContent = await parentResponse.Content.ReadAsStringAsync();
                        JObject parentJson = JObject.Parse(parentResponseContent);
                        
                        // 检查响应状态码
                        string parentCode = parentJson["Code"]?.ToString();
                        if (parentCode == "200")
                        {
                            // 获取父BOM数据
                            JObject parentData = parentJson["Data"] as JObject;
                            if (parentData != null)
                            {
                                // 获取父BOM的类型
                                string parentBomType = parentData["BomType"]?.ToString();
                                
                                // 如果父BOM类型不在层级字典中，无法验证，默认通过
                                if (!_bomTypeHierarchy.ContainsKey(parentBomType))
                                {
                                    return true;
                                }
                                
                                // 获取父BOM类型的层级
                                int parentTypeLevel = _bomTypeHierarchy[parentBomType];
                                
                                // 验证子BOM类型的层级是否低于父BOM类型的层级（数字更大表示层级更低）
                                if (childTypeLevel <= parentTypeLevel)
                                {
                                    Console.WriteLine($"验证失败：父BOM类型: {parentBomType}(层级{parentTypeLevel})，子BOM类型: {childBomType}(层级{childTypeLevel})");
                                    return false;
                                }
                                
                                Console.WriteLine($"验证通过：父BOM类型: {parentBomType}(层级{parentTypeLevel})，子BOM类型: {childBomType}(层级{childTypeLevel})");
                            }
                        }
                    }
                }
                
                // 如果无法获取父BOM信息，默认通过验证
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"验证子BOM类型异常: {ex.Message}");
                // 发生异常时，默认通过验证
                return true;
            }
        }

        /// <summary>
        /// 保存按键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取表单数据
                string bomCode = textEdit1.Text.Trim();
                string bomName = textEdit2.Text.Trim();
                string bomVersion = textEdit3.Text.Trim();
                string bomDescription = textEdit4.Text.Trim();
                
                // 验证必填字段
                if (string.IsNullOrEmpty(bomCode))
                {
                    XtraMessageBox.Show("请选择产品编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEdit1.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(bomName))
                {
                    XtraMessageBox.Show("产品名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEdit2.Focus();
                    return;
                }
                
                if (string.IsNullOrEmpty(bomVersion))
                {
                    XtraMessageBox.Show("版本号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEdit3.Focus();
                    return;
                }
                
                // 根据编码获取BOM类型和阶别
                var typeRank = GetBomTypeAndRankByCode(bomCode);
                string bomType = typeRank.Item1;
                string bomRank = typeRank.Item2;
                
                // 如果是添加子BOM模式，验证BOM类型是否合法
                if (_isAddChildMode && _parentBomId > 0)
                {
                    // 验证子BOM类型
                    bool isValidType = await ValidateChildBomType(_parentBomId, bomType);
                    if (!isValidType)
                    {
                        XtraMessageBox.Show($"无法添加{bomType}作为子项，子项类型必须比父项类型低级", "类型错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    
                    try
                    {
                        // 构建API URL来获取父BOM信息
                        string parentUrl = $"api/Bom/GetBomById?id={_parentBomId}";
                        
                        // 使用同步方式获取父BOM信息
                        using (HttpClient parentClient = new HttpClient())
                        {
                            parentClient.BaseAddress = new Uri(ApiBaseUrl);
                            parentClient.Timeout = TimeSpan.FromSeconds(30);
                            
                            // 发送GET请求
                            HttpResponseMessage parentResponse = parentClient.GetAsync(parentUrl).Result;
                            
                            if (parentResponse.IsSuccessStatusCode)
                            {
                                string parentResponseContent = parentResponse.Content.ReadAsStringAsync().Result;
                                JObject parentJson = JObject.Parse(parentResponseContent);
                                
                                // 检查响应状态码
                                string parentCode = parentJson["Code"]?.ToString();
                                if (parentCode == "200")
                                {
                                    // 获取父BOM数据
                                    JObject parentData = parentJson["Data"] as JObject;
                                    if (parentData != null)
                                    {
                                        // 获取父BOM的阶别
                                        string parentRank = parentData["Bomranks"]?.ToString() ?? "0";
                                        int parentRankInt = 0;
                                        if (int.TryParse(parentRank, out parentRankInt))
                                        {
                                            // 子BOM的阶别 = 父BOM的阶别 + 1
                                            bomRank = (parentRankInt + 1).ToString();
                                            Console.WriteLine($"父BOM阶别: {parentRank}, 子BOM阶别: {bomRank}");
                                        }
                                        else
                                        {
                                            // 如果无法解析父阶别，默认子阶别为1
                                            bomRank = "1";
                                            Console.WriteLine($"无法解析父BOM阶别: {parentRank}, 使用默认子BOM阶别: 1");
                                        }
                                    }
                                    else
                                    {
                                        // 如果无法获取父BOM数据，默认子阶别为1
                                        bomRank = "1";
                                        Console.WriteLine("无法获取父BOM数据，使用默认子BOM阶别: 1");
                                    }
                                }
                                else
                                {
                                    // 如果API返回错误，默认子阶别为1
                                    string message = parentJson["Message"]?.ToString() ?? "未知错误";
                                    Console.WriteLine($"获取父BOM信息失败: {message}, 使用默认子BOM阶别: 1");
                                    bomRank = "1";
                                }
                            }
                            else
                            {
                                // 如果API请求失败，默认子阶别为1
                                Console.WriteLine($"获取父BOM信息请求失败，状态码: {parentResponse.StatusCode}, 使用默认子BOM阶别: 1");
                                bomRank = "1";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 如果发生异常，默认子阶别为1
                        Console.WriteLine($"获取父BOM信息异常: {ex.Message}, 使用默认子BOM阶别: 1");
                        bomRank = "1";
                    }
                }
                
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 确定是新增还是编辑操作
                bool isEdit = _currentBom != null;
                
                // 创建或更新BOM模型
                Bommodel bom;
                
                if (isEdit)
                {
                    // 编辑模式：保留原有BOM的所有属性，只更新表单中的字段
                    bom = _currentBom;
                    
                    // 只更新表单中的字段
                    bom.Bomcode = bomCode;
                    bom.Bomname = bomName;
                    bom.Bomversion = bomVersion;
                    bom.Bomdescription = bomDescription;
                    bom.BomType = bomType;
                    bom.Bomranks = bomRank;
                    bom.UpdatedTime = DateTime.Now;
                    bom.UpdatedBy = "system"; // 可以替换为实际的用户信息
                    
                    // 确保Productitemid也被更新
                    bom.Productitemid = bomCode;
                    
                    // 根据BOM类型更新工序信息
                    switch (bomType)
                    {
                        case "成品":
                            bom.Processmanagementcode = "P001";
                            bom.Processmanagementname = "无人机整机组装";
                            break;
                        case "半成品":
                            bom.Processmanagementcode = "P002";
                            bom.Processmanagementname = "无人机部件组装";
                            break;
                        case "原材料":
                            bom.Processmanagementcode = "P003";
                            bom.Processmanagementname = "原材料处理";
                            break;
                        default:
                            bom.Processmanagementcode = "P000";
                            bom.Processmanagementname = "未定义工序";
                            break;
                    }
                }
                else
                {
                    // 新增模式：创建新的BOM对象
                    bom = new Bommodel
                    {
                        Bomcode = bomCode,
                        Bomname = bomName,
                        Bomversion = bomVersion,
                        Bomdescription = bomDescription,
                        BomType = bomType,
                        Bomranks = bomRank,
                        CreatedTime = DateTime.Now,
                        CreatedBy = "system",
                        UpdatedTime = DateTime.Now,
                        UpdatedBy = "system",
                        IsDeleted = false,
                        Productitemid = bomCode,
                        Bomdosage = "1" // 用量默认为1
                    };
                    
                    // 如果是添加子BOM模式，设置父ID
                    if (_isAddChildMode && _parentBomId > 0)
                    {
                        bom.Parentid = _parentBomId;
                    }
                    
                    // 根据BOM类型设置工序信息
                    switch (bomType)
                    {
                        case "成品":
                            bom.Processmanagementcode = "P001";
                            bom.Processmanagementname = "无人机整机组装";
                            break;
                        case "半成品":
                            bom.Processmanagementcode = "P002";
                            bom.Processmanagementname = "无人机部件组装";
                            break;
                        case "原材料":
                            bom.Processmanagementcode = "P003";
                            bom.Processmanagementname = "原材料处理";
                            break;
                        default:
                            bom.Processmanagementcode = "P000";
                            bom.Processmanagementname = "未定义工序";
                            break;
                    }
                }
                
                // 将对象序列化为JSON
                string jsonData = JsonConvert.SerializeObject(bom);
                Console.WriteLine("请求JSON数据:");
                Console.WriteLine(jsonData);
                
                // 打印发送前的BOM对象信息（调试用）
                Console.WriteLine("发送请求前的BOM对象:");
                PrintBomDetails(bom);
                
                // 构建API URL - 根据操作类型确定
                string url;
                if (isEdit)
                {
                    // 确保ID正确传递
                    if (bom.Id <= 0)
                    {
                        XtraMessageBox.Show("无法更新BOM，ID无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Cursor = Cursors.Default;
                        return;
                    }
                    // 使用与添加相同的API端点，ID通过请求体传递
                    url = "api/Bom/UpdateBom";
                }
                else if (_isAddChildMode && _parentBomId > 0)
                {
                    // 先检查父BOM是否存在
                    bool parentExists = false;
                    try
                    {
                        string checkUrl = $"api/Bom/GetBomById?id={_parentBomId}";
                        using (HttpClient checkClient = new HttpClient())
                        {
                            checkClient.BaseAddress = new Uri(ApiBaseUrl);
                            HttpResponseMessage checkResponse = checkClient.GetAsync(checkUrl).Result;
                            
                            if (checkResponse.IsSuccessStatusCode)
                            {
                                string checkContent = checkResponse.Content.ReadAsStringAsync().Result;
                                JObject checkJson = JObject.Parse(checkContent);
                                
                                if (checkJson["Code"]?.ToString() == "200" && checkJson["Data"] != null)
                                {
                                    parentExists = true;
                                    Console.WriteLine($"父BOM存在，ID: {_parentBomId}");
                                }
                                else
                                {
                                    Console.WriteLine($"父BOM不存在，ID: {_parentBomId}，错误信息: {checkJson["Message"]}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"检查父BOM异常: {ex.Message}");
                    }
                    
                    if (!parentExists)
                    {
                        // 如果父BOM不存在，提示用户并询问是否继续添加为顶级BOM
                        DialogResult result = XtraMessageBox.Show(
                            $"父级BOM(ID: {_parentBomId})不存在或无法访问。\n\n是否将此BOM添加为顶级BOM？", 
                            "父级BOM不存在", 
                            MessageBoxButtons.YesNo, 
                            MessageBoxIcon.Question);
                            
                        if (result == DialogResult.Yes)
                        {
                            // 用户选择添加为顶级BOM
                            _isAddChildMode = false;
                            bom.Parentid = 0; // 清除父ID
                            url = "api/Bom/AddBom"; // 使用普通添加接口
                            Console.WriteLine("用户选择添加为顶级BOM");
                        }
                        else
                        {
                            // 用户取消操作
                            XtraMessageBox.Show("操作已取消", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Cursor = Cursors.Default;
                            return;
                        }
                    }
                    else
                    {
                        // 父BOM存在，使用添加子BOM的API端点
                        url = $"api/Bom/AddChildBom?parentId={_parentBomId}";
                    }
                }
                else
                {
                    url = "api/Bom/AddBom";
                }
                
                Console.WriteLine($"请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 创建HTTP内容
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    
                    // 发送请求 - 统一使用POST请求
                    HttpResponseMessage response;
                    if (isEdit)
                    {
                        // 编辑模式也使用POST请求
                        Console.WriteLine("发送POST请求更新BOM");
                        
                        // 确保请求头设置正确
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                        
                        response = await client.PostAsync(url, content);
                    }
                    else
                    {
                        // 新增模式使用POST请求
                        Console.WriteLine("发送POST请求添加BOM");
                        response = await client.PostAsync(url, content);
                    }
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应内容: {responseContent}");
                        Console.WriteLine($"HTTP状态码: {response.StatusCode}");
                        
                        // 解析JSON响应
                        JObject jsonResponse = JObject.Parse(responseContent);
                        
                        // 检查响应状态码
                        string code = jsonResponse["Code"]?.ToString();
                        if (code == "200")
                        {
                            string successMessage = isEdit ? "更新成功" : (_isAddChildMode ? "添加下级成功" : "添加成功");
                            XtraMessageBox.Show(successMessage, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 刷新父窗体数据
                            if (_parentForm != null)
                            {
                                _parentForm.RefreshData();
                            }
                            
                            // 关闭当前窗体
                            this.Close();
                        }
                        else
                        {
                            string operationType = isEdit ? "更新" : (_isAddChildMode ? "添加下级" : "添加");
                            string message = jsonResponse["Message"]?.ToString() ?? $"{operationType}失败";
                            XtraMessageBox.Show($"{operationType}失败: {message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // 读取错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API错误响应: {errorContent}");
                        Console.WriteLine($"HTTP状态码: {response.StatusCode}");
                        
                        // 尝试解析错误响应
                        try
                        {
                            JObject errorJson = JObject.Parse(errorContent);
                            string errorMessage = errorJson["Message"]?.ToString() ?? "未知错误";
                            string operationType = isEdit ? "更新" : (_isAddChildMode ? "添加下级" : "添加");
                            XtraMessageBox.Show($"{operationType}失败: {errorMessage}\nHTTP状态码: {response.StatusCode}", 
                                "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        catch
                        {
                            // 如果无法解析JSON，则显示原始错误内容
                            string operationType = isEdit ? "更新" : (_isAddChildMode ? "添加下级" : "添加");
                            XtraMessageBox.Show($"{operationType}失败，HTTP状态码: {response.StatusCode}\n{errorContent}", 
                                "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"保存数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
    }
}